import { loginAPI, userInfoAPI, userPhotoAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户名
  SET_USER(state, value) {
    state.userInfo = value
  },
  // 删除用户信息
  REMOVE_USER(state) {
    state.userInfo = {}
  }

}

const actions = {
  async loginActions({ commit }, data) {
    const res = await loginAPI(data)
    commit('SET_TOKEN', res.data)
    return res
  },
  async userInfoActions({ commit }) {
    const { data: userObj } = await userInfoAPI()
    const { data: photoObj } = await userPhotoAPI(userObj.userId)

    commit('SET_USER', { ...userObj, ...photoObj })
    return userObj.roles.menus// 返回页面权限点
  },
  logoutActions({ commit }) {
    commit('REMOVE_TOKEN')
    commit('REMOVE_USER')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

